<?php
namespace app\admin\controller;

use app\admin\validate\HomeCate;
use app\common\entity\User;
use app\common\shop\HomeCateModel;
use think\Db;
use think\Request;
use think\Controller;
use app\admin\exception\AdminException;
use app\common\shop\ShopGoodsModel;
use app\common\shop\SpecModel;
use app\common\shop\SpecListModel;
use app\common\entity\GoodsCategory;

class Shopgoods extends Admin {
    /**
     * [首页分类]
     * @param
     * @return
     */
    public function cate( Request $request ){
        $cate = new HomeCateModel();
        $list = $cate->order('id asc')->paginate(15, false, [
            'query'=>$request->param()  ? $request->param():[]
        ]);
        foreach ($list as $key => $value) {
            $list[$key]['img'] = unserialize($value['img'])[0];
        }
        return $this->render('cate', [
            'list' => $list,
        ]);
    }
    /**
     * [首页分类-添加]
     * @param
     * @return
     */
    public function createcate( Request $request ){
        return $this->render('editcate');
    }
    /**
     * [首页分类-添加保存]
     * @param
     * @return
     */
    public function savecate( Request $request ){
        $input = input();
        $result = $this->validate(input(), 'app\admin\validate\HomeCate');
        if (true !== $result) {
            return json()->data(['code' => 1, 'message' => $result]);
        }
        // 处理数据
        $cateid = HomeCateModel::dispose($input);
        return json(['code' => 0, 'toUrl' => url('/admin/shopgoods/cate')]);
    }
    /**
     * [首页分类-修改]
     * @param
     * @return
     */
    public function editcate( Request $request ){
        $id = input('id');
        $info = HomeCateModel::where('id',$id)->find();
        $info['imgs'] = unserialize($info['img']);
        return $this->render('editcate',[
            'info' => $info,
        ]);
    }
    /**
     * [首页分类-修改保存]
     * @param
     * @return
     */
    public function updatecate( Request $request ){
        $input = input();
        $result = $this->validate(input(), 'app\admin\validate\HomeCate');
        if (true !== $result) {
            return json()->data(['code' => 1, 'message' => $result]);
        }
        // 处理数据
        $cateid = HomeCateModel::dispose($input,input('id'));
        return json(['code' => 0, 'toUrl' => url('/admin/shopgoods/cate')]);
    }
    /**
     * [删除分类]
     * @param
     * @return
     */
    public function deletecate( Request $request ){
       $cateid = input('id');
       $cate = HomeCateModel::where('id',$cateid)->find();
       if(!$cate) return json()->data(['code'=>-1,'message'=>'分类不存在']);
       HomeCateModel::where('id',$cateid)->delete();
       return json(['code' => 0, 'message'=>'删除成功']);
    }

    /**
     * [商品列表]
     * @param
     * @return
     */
    public function index( Request $request ){
        $goods = ShopGoodsModel::alias('g');
        $where = [];
        if($shoptype = input('shoptype')){
            $goods->where('g.shoptype',$shoptype);
        }
        $list = $goods
                ->field('g.*,ga.category_title')
                ->where($where)
                ->leftJoin('goods_category ga','ga.category_id = g.cateid')
                ->order('g.id desc')
                ->paginate(15, false, [
                    'query'=>$request->param()  ? $request->param():[]
                ]);
        //echo $goods->getLastsql();
        foreach ($list as $key => $value) {
            $list[$key]['img'] = unserialize( $value['path'])[0];
        }

        return $this->render('index', [
            'list' => $list,
            'shoptype'=>(new ShopGoodsModel())->shoptype,
        ]);
    }

    /**
     * [添加商品]
     * @param
     * @return
     */
    public function addgoods( Request $request ){
        return $this->render('editgoods',[
            'cate'=>GoodsCategory::getAllCate(['shoptype'=>1]),
            'homecate'=>HomeCateModel::select(),
            'shoptype'=> (new ShopGoodsModel())->shoptype,
        ]);
    }

    /**
     * [修改商品]
     * @param
     * @return
     */
    public function editgoods( Request $request ){
        $id = input('id');
        $goods = ShopGoodsModel::getGoods($id);
        $goods['imgs'] = unserialize($goods['path']);
        $spec = SpecListModel::getList($id)->toArray();// 规格列表
        $spec_title = [];
        if($spec){
            // 规格
            $list = SpecModel::getGoodsSpec($spec);
            $spec= $list['spec'];
            $spec_title= $list['spec_title'];
        }
        $goods['spec'] = json_encode($spec);
        $spec_list = SpecModel::getList($id)->toArray();


        return $this->render('editgoods',[
            'info' => $goods,
            'spec_title'=>$spec_title,
            'spec_list'=>json_encode($spec_list),
            'cate'=>GoodsCategory::getAllCate(['shoptype'=>$goods['shoptype']]),
            'homecate'=>HomeCateModel::select(),
            'shoptype'=> (new ShopGoodsModel())->shoptype,
        ]);
    }
    /**
     * [获取分类]
     * @param
     * @return
     */
    public function getcate( Request $request ){
        $shoptype = input('shoptype');
        $cate = GoodsCategory::getAllCate(['shoptype'=>$shoptype]);
        return json(['code' => 0, 'message' => '完成','info'=>$cate]);
    }
    /**
     * [删除商品]
     * @param
     * @return
     */
    public function delgoods( Request $request ){
        $id = input('id');
        if(empty($id)) return json(['code'=>1,'message'=>'参数错误']);
        $goods = ShopGoodsModel::getGoods($id);
        if(empty($goods)) return json(['code'=>1,'message'=>'商品不存在，请刷新重试']);
        $goods->delete();
        return json(['code' => 0, 'message' => '完成']);
    }
    /**
     * [保存商品-添加]
     * @param
     * @return
     */
    public function savegoods( Request $request ){
        $input = input();
        $result = $this->validate(input(), 'app\admin\validate\ShopGoodsSave');
        if (true !== $result) {
            return json()->data(['code' => 1, 'message' => $result]);
        }
        if($input['shoptype'] == 3 && $input['groupnumber'] <=0){
            return json(['code' => 1, 'message' => '拼团商品拼团人数不能小于0']);
        }
        // 处理数据-添加商品
        $goodsid = ShopGoodsModel::dispose($input);

        // 规格处理
        if(empty($input['pps'])){
            SpecListModel::where('goodsid',$goodsid)->delete();// 删除规格
        }else{
            SpecListModel::dispoSespecList($input['pps'],$goodsid);
        }
        return json(['code'=>0,'message'=>'成功','toUrl'=>url('/admin/shopgoods/index')]);
    }
    /**
     * [保存商品-修改]
     * @param
     * @return
     */
    public function editsavegoods( Request $request ){
        $input = input();
        $result = $this->validate(input(), 'app\admin\validate\ShopGoodsSave');
        if (true !== $result) {
            return json()->data(['code' => 1, 'message' => $result]);
        }
        if($input['shoptype'] == 3 && $input['groupnumber'] <=0){
            return json(['code' => 1, 'message' => '拼团商品拼团人数不能小于0']);
        }
        // 处理数据-添加商品
        $goodsid = ShopGoodsModel::dispose($input,input('id'));

        // 规格处理
        if(empty($input['pps'])){
            SpecListModel::where('goodsid',$goodsid)->delete();// 删除规格
        }else{
            SpecListModel::dispoSespecList($input['pps'],$goodsid);
        }
        return json(['code'=>0,'message'=>'成功','toUrl'=>url('/admin/shopgoods/index')]);

    }
    /**
     * [规格新建]
     * @param
     * @return
     */
    public function selectspec( Request $request ){
        $goodsid = input('goodsid');
        return json(['code'=>0,'message'=>'请求成功','data'=>SpecModel::getList($goodsid)]);
    }

    /**
     * [添加规格]
     * @return
     */
    public function addspec(){
        $title = input('val');
        if(empty($title)){
            return json(['code'=>1,'message'=>'名称不能为空']);
        }

        $pid = input('pid')??0;
        $goodsid = input('goodsid')??0;

        if(!($id = SpecModel::where('title',$title)->where('goodsid',$goodsid)->where('pid',$pid)->value('id') )){
            $id = SpecModel::add(['pid'=>$pid,'title'=>$title,'goodsid'=>$goodsid]);
        }

        return json(['code'=>0,'message'=>'请求成功','data'=>['id'=>$id]]);
    }

    /**
     * [是否存在规格-返回列表]
     * @return
     */
    public function checkspec(){
        $id = input('id');
        $count = SpecModel::where('id',$id)->where('pid',0)->count();
        if(empty($count)) return json(['code'=>1,'message'=>'没有数据']);
        return json(['code'=>0,'message'=>'请求成功','data'=>SpecModel::where('pid',$id)->select()]);
    }

    /**
     * [删除规格]
     * @return
     */
    public function ppvdel(){
        $id = input('id');
        // 10 , 10_ , _10 , _10_
        $info = SpecListModel::whereOr('key',$id)->whereOr('key','like',$id.'_%')->whereOr('key','like','%_'.$id)->whereOr('key','like','%_'.$id.'_%')->find();
        if($info) return json(['code'=>1,'message'=>'该规格存在商品正在使用，不能删除']);
        SpecModel::where('id',$id)->delete();
        return json(['code'=>0,'message'=>'完成']);
    }

    /**
     * [删除规格]
     * @return
     */
    public function ppkdel(){
        $id = input('id');
        $info = SpecModel::where('id',$id)->find();
        $pid_list = collection(SpecModel::getPidSpec($info['id']))->toArray();
        if($pid_list){
            foreach ($pid_list as $key => $value) {
                $info_pec = SpecListModel::whereOr('key',$value['id'])->whereOr('key','like',$value['id'].'_%')->whereOr('key','like','%_'.$value['id'])->whereOr('key','like','%_'.$value['id'].'_%')->find();
                if($info_pec){
                    return json(['code'=>1,'message'=>'该规格存在商品正在使用，不能删除']);
                }
            }
        }
        SpecModel::where('id',$id)->delete();
        return json(['code'=>0,'message'=>'完成']);
    }
}